package com.wang.controller;



import com.wang.domain.Book;
import com.wang.service.BookService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//@RestController  =controller+responseBody将return的东西转成json
//@RequestBody用于接收json数据
//@RequestParam用于接收url地址传参或者表单传参
//@PathVariable用于接收路径参数，使用{参数名称}描述路径参数

//get查询  post新增/保存  put修改/更新  delete删除
@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag=bookService.save(book);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR,flag);
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag=bookService.update(book);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR,flag);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag=bookService.delete(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR,flag);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Book book =bookService.getById(id);
        Integer code=book != null ? Code.GET_OK : Code.GET_ERR;
        String msg=book !=null ? "" : "数据查询失败，请重试！";
        return  new Result(code,book,msg);
    }

    @GetMapping
    public Result getAll() {
        List<Book> booklist =bookService.getAll();
        Integer code=booklist != null ? Code.GET_OK : Code.GET_ERR;
        String msg=booklist !=null ? "" : "数据查询失败，请重试！";
        return  new Result(code,booklist,msg);
    }
}
